import tools from "../../../tools"
import hierParentModel from './hierParentModel'
import util from "../../util"

export default class treeChainModel extends hierParentModel {
  constructor(hierProperties) {
    super(hierProperties, treeChainModel)
    this.recordsTree = []
    this.addRoot()
  }
  addRoot() {
    if (!this.find('nodeType', 'root')) {
      this.hierProperties.content.push(this.rootTpl())
    }
    this.formatTree()
  }
  formatTree() {
    this.recordsTree =  util.formatTree(
      util.deepCopy(this.hierProperties.content),
      this.hierProperties.content.filter(item => item.nodeType === 'root'),
      false, 'nodeId'
    )
    return this.recordsTree
  }
  // 保存前, 格式化content数据
  formatContent() {
    if (this.hierProperties.content && this.hierProperties.content.length) {
      this.hierProperties.content = this.hierProperties.content.map((item, index) => {
        let nextItem = this.hierProperties.content[index +1]
        delete item.children
        let res = {
          ...item,
          nodeType: item.name === 'root' ? 'root' :
            !!nextItem && (nextItem.parentId === item.nodeId) ? 'node' : item.nodeType
        }
        return res;
      })
    }
  }
  rootTpl() {
    return {
      nodeId: 'root',
      name: 'root',
      nodeType: 'root',
      parentId: '',
      properties: [],
      link:{},
    }
  }
  static tpl() {
    return {
      type: 'treeChain',
      content: [
        // item
      ]
    }
  }
  static itemTpl(data = {}) {
    return {
      nodeId: tools.uuid(),
      parentId: '',
      nodeType: "leaf",  //['root', 'list', 'dictionary', 'leaf']
      name: '新增节点',
      properties: [],
      statusProperties: [],
      link:{
      },
      ...data
    }
  }
}